<?php
/**
 * Created by PhpStorm.
 * User: 000
 * Date: 2024/10/20
 * Time: 13:38
 */

namespace App\Constant;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use App\Models\SmsLogs;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
class SendMess
{
    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public static function createClient(){
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $TemplateParam = array("code"=>$args['code']);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $args['phone_num'],
            "templateCode" => getenv("ALIBABA_CLOUD_TEMPLATE_CODE"),
            "signName" => getenv("ALIBABA_CLOUD_SIGN_NAME"),
            "templateParam"=>json_encode($TemplateParam)
        ]);
        try {
            // 复制代码运行请自行打印 API 的返回值
          $result =  $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
          if($result->statusCode == 200){
                //设置缓存
              Cache::put($args['phone_num']. 'code', $args['code'], 10);
              $sms = new SmsLogs();
              $sms->phone = $args['phone_num'];
              $sms->code = $args['code'];
              $sms->ins_time = date("Y-m-d H:i:s",time());
              $sms->ip = $_SERVER['REMOTE_ADDR'];;
              $sms->save();
              return $result->statusCode;
          }
          $content = $result->body;
          return $content;
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }


    public function getIpAddress(Request $request)
    {
        $ip = $request->ip();
        // 或者可以直接访问 $request->getClientIp() 方法
        // $ip = $request->getClientIp();

        return $ip;
    }


}